﻿using System.Text.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace DifyToOpenAI.Models
{



    /// <summary>
    /// 表示聊天补全请求的类。
    /// Represents a class for chat completion requests.
    /// </summary>
    public class ChatCompletionRequest
    {
        /// <summary>
        /// 包含对话历史记录的消息列表。
        /// A list of messages comprising the conversation so far.
        /// </summary>
        public List<ChatMessage>? messages { get; set; } = new List<ChatMessage>();

        /// <summary>
        /// 要使用的模型ID。
        /// ID of the model to use.
        /// </summary>
        public string? model { get; set; }

        /// <summary>
        /// 频率惩罚系数。
        /// The frequency penalty coefficient.
        /// </summary>
        public double? frequency_penalty { get; set; }

        /// <summary>
        /// 存在惩罚系数。
        /// The presence penalty coefficient.
        /// </summary>
        public double? presence_penalty { get; set; }

        /// <summary>
        /// 是否使用流式传输。
        /// Whether to stream back partial progress.
        /// </summary>
        public bool stream { get; set; }=false;

        /// <summary>
        /// 采样的温度。
        /// The sampling temperature to use.
        /// </summary>
        public double? temperature { get; set; }

        /// <summary>
        /// 使用核心采样的概率质量。
        /// The probability mass to use for nucleus sampling.
        /// </summary>
        public double? top_p { get; set; }

        /// <summary>
        /// 生成的最大令牌数。
        /// The maximum number of tokens to generate.
        /// </summary>
        public int? max_tokens { get; set; }

        /// <summary>
        /// 为每个输入消息生成的聊天补全次数。
        /// How many chat completion choices to generate for each input message.
        /// </summary>
        public int? n { get; set; }

        /// <summary>
        /// API将停止生成更多令牌的序列。
        /// Sequences where the API will stop generating further tokens.
        /// </summary>
        public object? stop { get; set; }

        /// <summary>
        /// 修改指定令牌出现的可能性。
        /// Modify the likelihood of specified tokens appearing in the completion.
        /// </summary>
        public object? logit_bias { get; set; }

        /// <summary>
        /// 是否返回输出令牌的日志概率。
        /// Whether to return log probabilities of the output tokens.
        /// </summary>
        public bool? logprobs { get; set; }

        /// <summary>
        /// 指定要返回的最可能令牌数。
        /// An integer specifying the number of most likely tokens to return.
        /// </summary>
        public int? top_logprobs { get; set; }

        /// <summary>
        /// 指定模型必须输出的格式的对象。
        /// An object specifying the format that the model must output.
        /// </summary>
        public ResponseFormat? response_format { get; set; }

        /// <summary>
        /// 用于可重复采样的种子。
        /// Seed for repeatable sampling.
        /// </summary>
        public long? seed { get; set; }

        /// <summary>
        /// 模型可能调用的工具列表。
        /// A list of tools the model may call.
        /// </summary>
        public object? tools { get; set; }

        /// <summary>
        /// 控制模型如何调用工具。
        /// Controls how the model calls tools.
        /// </summary>
        public object? tool_choice { get; set; }

        /// <summary>
        /// 代表您的最终用户的唯一标识符。
        /// A unique identifier representing your end-user.
        /// </summary>
        public string? user { get; set; }


        [JsonIgnore]
        private string realJsonstring = string.Empty;

        /// <summary>
        /// 获取或设置请求的真实 JSON 字符串表示。设置此属性将触发反序列化。
        /// Gets or sets the real JSON string representation of the request. Setting this property will trigger deserialization.
        /// </summary>
        [JsonIgnore]
        public string? RealJsonstring
        {
            get { return realJsonstring; }
            set
            {
                realJsonstring = value!;
                try
                {
                    DeserializeChatCompletionRequest(value!);
                }
                catch (Exception)
                {
                    // 可以选择记录异常或按需处理
                    // Optionally log the exception or handle it as needed
                }
            }
        }

        /// <summary>
        /// 将 JSON 字符串反序列化到当前的 ChatCompletionRequest 实例中。
        /// 此方法逐个解析 JSON 属性，即使某些属性解析失败，也会继续尝试解析其他属性。
        /// Deserializes a JSON string into the current ChatCompletionRequest instance.
        /// This method parses JSON properties one by one, continuing even if some fail.
        /// </summary>
        /// <param name="json">需要解析的 JSON 字符串。The JSON string to be parsed.</param>
        public virtual void DeserializeChatCompletionRequest(string json)
        {
            if (string.IsNullOrEmpty(json)) return;
            var jsonNode = JsonNode.Parse(json);
            if (jsonNode == null) return;

            // --- 解析 messages 数组 ---
            try
            {
                var messagesNode = jsonNode["messages"]?.AsArray();
                if (messagesNode != null)
                {
                    this.messages = new List<ChatMessage>();
                    foreach (var msgNode in messagesNode)
                    {
                        if (msgNode == null) continue;
                        var chatMessage = new ChatMessage();
                        try { chatMessage.role = msgNode["role"]?.GetValue<string>(); } catch { }
                        try { 

                           // chatMessage.content = msgNode["content"]?.GetValue<string>();
                            chatMessage.content = Convert.ToString(msgNode["content"]);

                        } catch { }
                        this.messages.Add(chatMessage);
                    }
                }
            }
            catch { }

            // --- 解析简单类型的属性 ---
            try { if (jsonNode["model"] != null) this.model = jsonNode["model"]!.GetValue<string>(); } catch { }
            try { if (jsonNode["frequency_penalty"] != null) this.frequency_penalty = jsonNode["frequency_penalty"]!.GetValue<double>(); } catch { }
            try { if (jsonNode["presence_penalty"] != null) this.presence_penalty = jsonNode["presence_penalty"]!.GetValue<double>(); } catch { }
            try { if (jsonNode["stream"] != null) this.stream = jsonNode["stream"]!.GetValue<bool>(); } catch { }
            try { if (jsonNode["temperature"] != null) this.temperature = jsonNode["temperature"]!.GetValue<double>(); } catch { }
            try { if (jsonNode["top_p"] != null) this.top_p = jsonNode["top_p"]!.GetValue<double>(); } catch { }
            try { if (jsonNode["max_tokens"] != null) this.max_tokens = jsonNode["max_tokens"]!.GetValue<int>(); } catch { }
            try { if (jsonNode["n"] != null) this.n = jsonNode["n"]!.GetValue<int>(); } catch { }
            try { if (jsonNode["logprobs"] != null) this.logprobs = jsonNode["logprobs"]!.GetValue<bool>(); } catch { }
            try { if (jsonNode["top_logprobs"] != null) this.top_logprobs = jsonNode["top_logprobs"]!.GetValue<int>(); } catch { }
            try { if (jsonNode["seed"] != null) this.seed = jsonNode["seed"]!.GetValue<long>(); } catch { }
            try { if (jsonNode["user"] != null) this.user = jsonNode["user"]!.GetValue<string>(); } catch { }

            // --- 解析可以为复杂对象的属性 ---
            try { if (jsonNode["stop"] != null) this.stop = jsonNode["stop"]!.ToJsonString(); } catch { }
            try { if (jsonNode["logit_bias"] != null) this.logit_bias = jsonNode["logit_bias"]!.ToJsonString(); } catch { }
            try { if (jsonNode["tools"] != null) this.tools = jsonNode["tools"]!.ToJsonString(); } catch { }
            try { if (jsonNode["tool_choice"] != null) this.tool_choice = jsonNode["tool_choice"]!.ToJsonString(); } catch { }

            // --- 解析 response_format 对象 ---
            try
            {
                var formatNode = jsonNode["response_format"];
                if (formatNode != null)
                {
                    this.response_format = new ResponseFormat();
                    try { this.response_format.type = formatNode["type"]?.GetValue<string>(); } catch { }
                }
            }
            catch { }
        }
    }

    /// <summary>
    /// 表示聊天消息的类。
    /// Represents a class for a chat message.
    /// </summary>
    public class ChatMessage
    {
        /// <summary>
        /// 消息发送者的角色 ("system", "user", or "assistant")。
        /// The role of the message's author ("system", "user", or "assistant").
        /// </summary>
        public string? role { get; set; }

        /// <summary>
        /// 消息的内容。
        /// The contents of the message.
        /// </summary>
        public string? content { get; set; }
    }

    /// <summary>
    /// 指定模型输出格式的类。
    /// A class that specifies the format for the model's output.
    /// </summary>
    public class ResponseFormat
    {
        /// <summary>
        /// 输出的类型，例如 "text" 或 "json_object"。
        /// The type of output, e.g., "text" or "json_object".
        /// </summary>
        public string? type { get; set; }
    }
}
